package com.zq.it.cms.common.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class CommUtil {

	private CommUtil() {
		
	}

	/**
	 * 根据传入的格式得到格式化的时间
	 */
	public static String formatDate(Date date,String pattern){
		if(date==null)
			return null;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}
	
	 /**
	  * 转换任意格式的日期
	 */
	public static Date parseDate(String date){
		if(StringUtils.isEmpty(date))
			return null;
        Date result=null;
        String parse=date;
        parse=parse.replaceFirst("^[0-9]{4}([^0-9])", "yyyy$1");
        parse=parse.replaceFirst("^[0-9]{2}([^0-9])", "yy$1");
        parse=parse.replaceFirst("([^0-9])[0-9]{1,2}([^0-9])", "$1MM$2");
        parse=parse.replaceFirst("([^0-9])[0-9]{1,2}( ?)", "$1dd$2");
        parse=parse.replaceFirst("( )[0-9]{1,2}([^0-9])", "$1HH$2");
        parse=parse.replaceFirst("([^0-9])[0-9]{1,2}([^0-9])", "$1mm$2");
        parse=parse.replaceFirst("([^0-9])[0-9]{1,2}([^0-9]?)", "$1ss$2");
        SimpleDateFormat format=new SimpleDateFormat(parse);
        try {
			result = format.parse(date);
		} catch (ParseException e) {
		}
        return result;
    }
	
	/**
	 * 比较两个日期date1 date2  yyyy-MM-dd
	 * 如果date1 > date2  返回 1
	 * 如果date2 > date1 返回 -1
	 * 如果相等 返回 0
	 */
	public static int compareDate(String date1,String date2){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
		return 0;
	}
	
	/**
	 * 比较两个日期date1 date2  
	 * 如果date1 > date2  返回 1
	 * 如果date2 > date1 返回 -1
	 * 如果相等 返回 0
	 */
	public static int compareDate(Date date1,Date date2){
		try {
			if (date1.getTime() > date2.getTime()) {
				return 1;
			} else if (date1.getTime() < date2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 处理月份
	 */
	public static Date addMonth(Date date,int amount){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONTH, amount);
		return c.getTime();
	}
	
	/**
	 * 处理年、月、日
	 */
	public static Date addYMD(Date date,int y,int m,int d){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.YEAR,y);
        c.add(Calendar.MONTH,m);
        c.add(Calendar.DAY_OF_YEAR,d);
		return c.getTime();
	}
	
	/**
	 * 根据格式获取当前时间字符串
	 */
	public static String getCurrentTime(String pattern){
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(new Date());
	}
	
	public static int parseDate(String type, Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		if (type.equals("y")) {
			return cal.get(Calendar.YEAR);
		}
		if (type.equals("M")) {
			return cal.get(Calendar.MONTH) + 1;
		}
		if (type.equals("d")) {
			return cal.get(Calendar.DAY_OF_MONTH);
		}
		if (type.equals("H")) {
			return cal.get(Calendar.HOUR_OF_DAY);
		}
		if (type.equals("m")) {
			return cal.get(Calendar.MINUTE);
		}
		if (type.equals("s")) {
			return cal.get(Calendar.SECOND);
		}
		return 0;
	}

	public static String toLongDate(Object v) {
		if (v == null || v.equals(""))
			return "";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(v);
	}

	public static String toShortDate(Object v) {
		if (v == null)
			return null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(v);
	}
	
	public static int toInt(Object s) {
		int v = 0;
		if (s != null)
			try {
				v = Integer.parseInt(s.toString());
			} catch (Exception e) {
			}
		return v;
	}
	
	public static float toFloat(Object s) {
		float v = 0.0f;
		if (s != null)
			try {
				v = Float.parseFloat(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static double toDouble(Object s) {
		double v = 0.0;
		if (s != null)
			try {
				v = Double.parseDouble(toString(s));
			} catch (Exception e) {
			}
		return v;
	}

	public static boolean toBoolean(Object s) {
		boolean v = false;
		if (s != null)
			try {
				v = Boolean.parseBoolean(s.toString());
			} catch (Exception e) {
			}
		return v;
	}

	public static String toString(Object s) {
		return s == null ? "" : s.toString().trim();
	}

	public static Long toLong(Object s) {
		Long v = -1l;
		if (s != null)
			try {
				v = Long.parseLong(s.toString());
			} catch (Exception e) {
				
			}
		return v;
	}

	public static BigDecimal toBigDecimal(Object s) {
		BigDecimal v = new BigDecimal("0");
		if (s != null) {
			try {
				v = new BigDecimal(toString(s));
			} catch (Exception e) {
				//
			}
		}
		return v;
	}

	/**
	 * 是否是手机号
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		if(StringUtils.isNotBlank(mobiles) && mobiles.length() == 11){
			String mobile = "^(1[3-9][0-9])\\d{8}$";
			Pattern p = Pattern.compile(mobile);
			Matcher m = p.matcher(mobiles);
			return m.matches();
		}else{
			return false;
		}
	}
	
	/**
	 * 获取某个超链接中的参数值
	 * @param url
	 * @param name
	 * @return
	 */
	public static String getUrlParam(String url,String name){
		String urlzz = "(^|\\?|&)"+ name +"=([^&]*)(&|$)";
		Pattern p = Pattern.compile(urlzz);
		Matcher m = p.matcher(url);
		while(m.find()){
			return m.group();
	    }
		return null;
	}
	
	/**
     * 下划线转驼峰法
     * @param line 源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
    
    /**
     * 驼峰法转下划线
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(word.toLowerCase());
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }
    
    /**
     * 将map中的key全部转换为驼峰命名
     * @param map
     * @return
     */
    public static Map<String, Object> changeKeyNamesToCamel(Map<String, Object> map){
    	Map<String, Object> result = new HashMap<>();
    	for (String key : map.keySet()) {
    		Object value = map.get(key);
			key = underline2Camel(key, true);
			result.put(key, value);
		}
    	return result;
    }

}
